package com.enba.boot.web.interceptor;

import com.enba.boot.core.context.SecurityContextHolder;
import com.enba.boot.web.properties.WebProperties;
import com.enba.boot.web.utils.HeaderUtils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.AsyncHandlerInterceptor;

public class SecurityContextInterceptor implements AsyncHandlerInterceptor {

  private final WebProperties webProperties;
  private final SecurityContextInterceptorCallback callback;

  public SecurityContextInterceptor(
      WebProperties webProperties, SecurityContextInterceptorCallback callback) {
    this.webProperties = webProperties;
    this.callback = callback;
  }

  @Override
  public boolean preHandle(
      HttpServletRequest request, HttpServletResponse response, Object handler) {
    if (!(handler instanceof HandlerMethod)) {
      return true;
    }

    // 从指定请求头获取值并设置到用户上下文中
    String headerValue = HeaderUtils.getHeader(request, webProperties.getHearName());
    if (StringUtils.hasText(headerValue)) {
      SecurityContextHolder.setKeyValue(webProperties.getHearName(), headerValue);
    }

    return callback.preHandle(request, response, handler);
  }

  @Override
  public void afterCompletion(
      HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
    SecurityContextHolder.remove();
  }
}
